<template>
  <div class="my-course-page">
    <div class="header">
      <h2>我的课程</h2>
    </div>

    <div class="filters">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">状态筛选:</div>
          <el-select v-model="courseStatusFilter" placeholder="请选择预约状态" clearable class="filter-select">
            <el-option label="全部状态" value=""></el-option>
            <el-option label="已预约" value="1"></el-option>
            <el-option label="已取消" value="2"></el-option>
            <el-option label="已完成" value="3"></el-option>
          </el-select>
        </div>

        <div class="filter-item">
          <div class="filter-label">上课日期:</div>
          <el-date-picker
              v-model="classDateFilter"
              type="date"
              placeholder="请选择上课日期"
              value-format="YYYY-MM-DD"
              class="filter-select"
          />
        </div>
      </div>

      <div class="filter-actions">
        <el-button type="primary" @click="applyFilters">筛选</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>
    </div>

    <div class="course-list">
      <el-table :data="filteredCourseList" stripe style="width: 100%" :show-header="true" @row-click="showCourseDetail">
        <el-table-column type="index" label="#" width="50" align="center"/>
        <el-table-column prop="courseName" label="课程" align="center"/>
        <el-table-column prop="coachName" label="教练" align="center"/>
        <el-table-column prop="classTime" label="上课时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.classTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="getCourseStatusLabel(scope.row.status).type" size="small">
              {{ getCourseStatusLabel(scope.row.status).text }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 课程详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="课程详情" width="90%" max-width="500px">
      <div class="course-detail" v-if="selectedCourse">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="课程名称">{{ selectedCourse.courseName }}</el-descriptions-item>
          <el-descriptions-item label="教练">{{ selectedCourse.coachName }}</el-descriptions-item>
          <el-descriptions-item label="上课时间">{{ formatDateTime(selectedCourse.classTime) }}</el-descriptions-item>
          <el-descriptions-item label="上课地点">{{ selectedCourse.room }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ formatDateTime(selectedCourse.reserveTime) }}</el-descriptions-item>
          <el-descriptions-item label="预约ID">{{ selectedCourse.reserveId }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getCourseStatusLabel(selectedCourse.status).type" size="small">
              {{ getCourseStatusLabel(selectedCourse.status).text }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button
              v-if="selectedCourse && selectedCourse.status === '1'"
              type="danger"
              @click="cancelReservation"
          >
            取消预约
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api.js'

// 课程状态筛选
const courseStatusFilter = ref('')

// 上课日期筛选
const classDateFilter = ref('')

// 弹窗可见性
const dialogVisible = ref(false)

// 选中的课程
const selectedCourse = ref(null)

// 课程列表数据
const courseList = ref([])

// 从后端获取课程数据
const fetchCourseList = async () => {
  try {
    const response = await api.get('/myCourse')
    if (response.success) {
      courseList.value = response.data.records
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
  }
}

// 根据状态和上课日期筛选课程
const filteredCourseList = computed(() => {
  let filtered = courseList.value

  // 状态筛选
  if (courseStatusFilter.value) {
    filtered = filtered.filter(course => course.status === courseStatusFilter.value)
  }

  // 上课日期筛选
  if (classDateFilter.value) {
    filtered = filtered.filter(course => {
      if (!course.classTime) return false
      const courseDate = course.classTime.split(' ')[0]
      return courseDate === classDateFilter.value
    })
  }

  return filtered
})

// 应用筛选条件
const applyFilters = () => {
  // 由于使用了 computed 属性，筛选会自动应用
  console.log('应用筛选条件:', { status: courseStatusFilter.value, classDate: classDateFilter.value })
}

// 重置筛选条件
const resetFilters = () => {
  courseStatusFilter.value = ''
  classDateFilter.value = ''
}

// 获取课程状态标签
const getCourseStatusLabel = (status) => {
  switch (status) {
    case '1':
      return { text: '已预约', type: 'primary' }
    case '2':
      return { text: '已取消', type: 'danger' }
    case '3':
      return { text: '已完成', type: 'success' }
    default:
      return { text: '未知', type: 'info' }
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return dateTime.replace(' ', '\n')
}

// 显示课程详情弹窗
const showCourseDetail = (row) => {
  selectedCourse.value = row
  dialogVisible.value = true
}

// 取消预约
const cancelReservation = async () => {
  if (!selectedCourse.value) return

  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
        `确定要取消预约课程 "${selectedCourse.value.courseName}" 吗？`,
        '确认取消预约',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    // 调用取消预约接口
    const response = await api({
      url: `/myCourse/changeReserve`,
      method: 'put',
      data: {
        reserveId: selectedCourse.value.reserveId // 正确使用 reserveId 字段
      }
    })

    if (response.success) {
      // 更新本地数据状态
      selectedCourse.value.status = '2' // 更新为已取消状态
      // 更新课程列表中的状态
      const courseIndex = courseList.value.findIndex(course => course.reserveId === selectedCourse.value.reserveId)
      if (courseIndex !== -1) {
        courseList.value[courseIndex].status = '2'
      }
      ElMessage.success('取消预约成功')
      dialogVisible.value = false

      try {
        await fetchCourseList()
      } catch (error) {
        console.error('获取更新后的课程列表失败:', error)
      }
    } else {
      ElMessage.error(response.message || '取消预约失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消预约失败')
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCourseList()
})
</script>

<style scoped>
.my-course-page {
  padding: 15px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 20px;
  padding: 10px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header h2 {
  margin: 0;
  color: #333;
}

.filters {
  margin-bottom: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

.filter-item {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 200px;
}

.filter-label {
  margin-right: 10px;
  font-weight: bold;
  white-space: nowrap;
}

.filter-select {
  flex: 1;
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.course-list {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

:deep(.el-table) {
  --el-table-header-bg-color: #f0f0f0;
  cursor: pointer;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-tag) {
  height: auto;
  padding: 4px 6px;
  line-height: 1;
}

.course-detail {
  padding: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-item {
    min-width: 100%;
  }

  .filter-label {
    width: 60px;
  }

  .filter-select {
    flex: auto;
  }
}
</style>
